TreeviewCopyright © aleen42 all right reserved, powered by aleen42

在 Android 中,使用 SharedPreferences 来存储一些简单的键值对,在 Flutter 中,使用 shared_preferences 插件来完成这一操作。

添加依赖

跟 Android 不一样,Flutter 在开始之前,需要在 pubspec.yaml 文件中添加 shared_preferences 插件:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: "<newest version>"

保存数据

和 Android 一样,需要先获取 SharedPreferences 对象:

SharedPreferences sp = await SharedPreferences.getInstance();

然后调用 SharedPreferences 对象的一系列 setXXX 方法:

  • setString
  • setBool
  • setDouble
  • setInt
  • setStringList

就不用一一解释含义了吧,有以下几点需要注意:

  1. 数据是被异步地保存到磁盘上
  2. 使用 setStringList 存储字符串 List 的时候,存储在 XML 文件中的 value 是加密过后的字符串
  3. 存储在 XML 文件中的 key 是以 flutter. 为前缀的
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="flutter.StringListKey">VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3QurO0ABXNyABNqYXZhLnV0aWwuQXJyYXlMaXN0eIHSHZnHYZ0DAAFJAARzaXpleHAAAAAEdwQAAAAE&#10;dAAEMTExMXQABDIyMjJ0AAQzMzMzdAAENDQ0NHg=&#10;    </string>
    <long name="flutter.IntKey" value="123" />
    <string name="flutter.StringKey">This is String</string>
    <boolean name="flutter.BoolKey" value="true" />
    <string name="flutter.DoubleKey">VGhpcyBpcyB0aGUgcHJlZml4IGZvciBEb3VibGUu123.0</string>
</map>

当有 XML 文件中有相同的 Key 时,则会替换原有的内容

读取数据

对于保存是使用 setXXX,读取自然是 getXXX 了:

  • get
  • getStringList
  • getString
  • getBool
  • getDouble
  • getInt
  • getKeys

依旧懒得解释。

删除数据

只有一个简单的 remove 方法,传入 key 即可。

示例

把官方的例子拿过来充数:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of the application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Shared preferences demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Shared preferences demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    _loadCounter();
  }

  //Loading counter value on start
  _loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (prefs.getInt('counter') ?? 0);
    });
  }

  //Incrementing counter after click
  _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (prefs.getInt('counter') ?? 0) + 1;
      prefs.setInt('counter', _counter);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

results matching ""

    No results matching ""